import React, { useEffect, useState } from 'react';
import { Card, Table, Button, DialogPlugin, MessagePlugin, Input, Select, Tag } from 'tdesign-react';
import { AddIcon, EditIcon, DeleteIcon, RefreshIcon, SettingIcon } from 'tdesign-icons-react';
import { JupiterPermission, JupiterPermissionQuery } from '../../types/permissionTypes';
import { JupiterDictionary } from '../../types/dictionaryTypes';
import { formatTime } from '../../utils/timeutil';
import {
  fetchPermissionList,
  createPermission,
  updatePermission,
  deletePermission,
  restorePermission,
} from '../../services/permissionService';
import { fetchActiveDictionariesByType } from '../../services/dictionaryService';
import PermissionForm from './components/PermissionForm';

const { Option } = Select;

export default function PermissionPage() {
  const [permissionList, setPermissionList] = useState<JupiterPermission[]>([]);
  const [loading, setLoading] = useState(false);
  const [formVisible, setFormVisible] = useState(false);
  const [editingPermission, setEditingPermission] = useState<Partial<JupiterPermission>>();
  const [title, setTitle] = useState('新增权限');
  const [searchName, setSearchName] = useState('');
  const [searchCode, setSearchCode] = useState('');
  const [searchType, setSearchType] = useState<string | undefined>();
  const [searchStatus, setSearchStatus] = useState<number | undefined>();
  const [permissionTypes, setPermissionTypes] = useState<JupiterDictionary[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  const getList = async () => {
    setLoading(true);
    try {
      const params: JupiterPermissionQuery = {
        name: searchName,
        code: searchCode,
        page: pagination.current,
        size: pagination.pageSize,
        ...(searchType !== undefined ? { type: Number(searchType) } : {}),
        ...(searchStatus !== undefined ? { status: searchStatus } : {}),
      };
      const res = await fetchPermissionList(params);
      if (res.data?.records) {
        setPermissionList(res.data.records || []);
        setPagination(prev => ({
          ...prev,
          total: res.data.total || 0,
        }));
      }
    } finally {
      setLoading(false);
    }
  };

  const fetchPermissionTypes = async () => {
    try {
      const response = await fetchActiveDictionariesByType('permission_type');
      if (response.data) {
        const sortedTypes = response.data.sort((a: JupiterDictionary, b: JupiterDictionary) => a.sortOrder - b.sortOrder);
        setPermissionTypes(sortedTypes);
      }
    } catch (error) {
      console.error('获取权限类型字典失败:', error);
    }
  };

  const handleCreate = () => {
    setEditingPermission(undefined);
    setTitle('新增权限');
    setFormVisible(true);
  };

  const handleEdit = (record: JupiterPermission) => {
    record.urlResourceUuids = record.urlResourceUuids || [];
    setEditingPermission(record);
    setTitle('编辑权限');
    setFormVisible(true);
  };

  const handleDelete = (record: JupiterPermission) => {
    const confirmDialog = DialogPlugin.confirm({
      header: '删除确认',
      body: `确定删除权限【${record.name}】？`,
      closeOnOverlayClick: false,
      onConfirm: async () => {
        await deletePermission(record.uuid);
        MessagePlugin.success('删除成功');
        getList();
        confirmDialog.hide();
      },
      onCancel: () => {
        confirmDialog.hide();
      },
      onClose: () => {
        confirmDialog.hide();
      },
    });
  };

  const handleRestore = (record: JupiterPermission) => {
    const confirmDialog = DialogPlugin.confirm({
      header: '恢复确认',
      closeOnOverlayClick: false,
      body: `确定恢复权限【${record.name}】？`,
      onConfirm: async () => {
        await restorePermission(record.uuid);
        MessagePlugin.success('恢复成功');
        getList();
        confirmDialog.hide();
      },
      onCancel: () => {
        confirmDialog.hide();
      },
      onClose: () => {
        confirmDialog.hide();
      },
    });
  };

  const handleSubmit = async (data: Partial<JupiterPermission>) => {
    if (editingPermission?.uuid) {
      await updatePermission(editingPermission.uuid, data);
      MessagePlugin.success('更新成功');
    } else {
      await createPermission(data);
      MessagePlugin.success('创建成功');
    }
    setFormVisible(false);
    getList();
  };

  const getTypeText = (type: string) => {
    const typeDict = permissionTypes.find(t => t.dictKey === type);
    return typeDict ? typeDict.dictLabel : '未知';
  };

  const getTypeColor = (type: string) => {
    switch (type) {
      case "menu":
        return 'primary';
      case "button":
        return 'success';
      case "api":
        return 'warning';
      default:
        return 'default';
    }
  };

  useEffect(() => {
    fetchPermissionTypes();
  }, []);

  useEffect(() => {
    getList();
  }, [pagination.current, pagination.pageSize, searchName, searchCode, searchType, searchStatus]);

  return (
    <Card title="权限管理">
      <div style={{ marginBottom: 16 }}>
        <div style={{ display: 'flex', gap: 16, marginBottom: 16 }}>
          <Input
            placeholder="搜索权限名称"
            value={searchName}
            onChange={(value) => setSearchName(value)}
            style={{ width: 150 }}
          />
          <Input
            placeholder="搜索权限编码"
            value={searchCode}
            onChange={(value) => setSearchCode(value)}
            style={{ width: 150 }}
          />
          <Select
            placeholder="选择类型"
            value={searchType}
            onChange={(value) => setSearchType(value as string)}
            clearable
            style={{ width: 120 }}
          >
            {permissionTypes.map((type) => (
              <Option key={type.uuid} value={type.dictKey} label={type.dictLabel}>
                {type.dictLabel}
              </Option>
            ))}
          </Select>
          <Select
            placeholder="选择状态"
            value={searchStatus}
            onChange={(value) => setSearchStatus(value as number)}
            clearable
            style={{ width: 120 }}
          >
            <Option value={1} label="启用">
              启用
            </Option>
            <Option value={0} label="禁用">
              禁用
            </Option>
          </Select>
          <Button theme="primary" onClick={getList}>
            查询
          </Button>
          <Button theme="primary" onClick={handleCreate}>
            新增权限
          </Button>
        </div>
      </div>

      <Table
        data={permissionList}
        rowKey="uuid"
        loading={loading}
        pagination={{
          current: pagination.current,
          pageSize: pagination.pageSize,
          total: pagination.total,
          showJumper: true,
          onChange: (pageInfo) => {
            setPagination(prev => ({
              ...prev,
              current: pageInfo.current,
              pageSize: pageInfo.pageSize,
            }));
          },
        }}
        columns={[
          {
            colKey: 'name',
            title: '权限名称',
            width: 150,
          },
          {
            colKey: 'code',
            title: '权限编码',
            width: 200,
          },
          {
            colKey: 'type',
            title: '类型',
            width: 100,
            cell: ({ row }) => (
              <Tag theme={getTypeColor(row.type) as any}>
                {getTypeText(row.type)}
              </Tag>
            ),
          },
          {
            colKey: 'sort',
            title: '排序',
            width: 80,
            cell: ({ row }) => <span>{row.sortIndex || 0}</span>,
          },
          {
            colKey: 'delete_status',
            title: '删除状态',
            width: 100,
            cell: ({ row }) => (
              <Tag theme={row.deleteTime ? 'danger' : 'success'}>
                {row.deleteTime ? '已删除' : '正常'}
              </Tag>
            ),
          },
          {
            colKey: 'description',
            title: '描述',
            width: 200,
            cell: ({ row }) => (
              <div style={{ maxWidth: 200, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                {row.description || '-'}
              </div>
            ),
          },
          {
            colKey: 'createTime',
            title: '创建时间',
            width: 180,
            cell: ({ row }) => formatTime(row.createTime || ""),
          },
          {
            colKey: 'operation',
            title: '操作',
            width: 180,
            cell: ({ row }) => (
              <>
                {row.deleteTime === null ? (
                  <>
                    <Button
                      theme="primary"
                      variant="text"
                      icon={<EditIcon />}
                      onClick={() => handleEdit(row)}
                    >
                      编辑
                    </Button>
                    <Button
                      theme="danger"
                      variant="text"
                      icon={<DeleteIcon />}
                      onClick={() => handleDelete(row)}
                    >
                      删除
                    </Button>
                  </>
                ) : (
                  <Button
                    theme="success"
                    variant="text"
                    icon={<RefreshIcon />}
                    onClick={() => handleRestore(row)}
                  >
                    恢复
                  </Button>
                )}
              </>
            ),
          }
        ]}
      />

      <PermissionForm
        visible={formVisible}
        onClose={() => setFormVisible(false)}
        onSubmit={handleSubmit}
        initialData={editingPermission}
        title={title}
      />
    </Card>
  );
}
